#include <string>

using std::string;
using std::reverse;

class Solution {
public:
    string reverseWords(string s) {
        reverse(s.begin(), s.end());
        int index = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] != ' ') {
                if (index != 0) {
                    s[index++] = ' ';
                }
                int k = i;
                while (k < s.size() && s[k] != ' ') {
                    s[index++] = s[k++];
                }
                reverse(s.begin() + index - (k - i), s.begin() + index);
                i = k;
            }
        }
        s.erase(s.begin() + index, s.end());
        return s;
    }
};